﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ThaiHoa.Win.QLSX.Entity;
using ThaiHoa.Win.QLSX.DAL;
using ThaiHoa.Win.QLSX.SanXuat.UTI;
using Excel = Microsoft.Office.Interop.Excel;

namespace ThaiHoa.Win.QLSX.SanXuat.UI
{
    public partial class frmCongDoanSanXuatList : Form
    {
        #region Fields
        KhoDBContext db;
        List<CongDoan> listCongDoan;
        DataTable dt;
        Access acs;

        #endregion
        #region Constructor
        public frmCongDoanSanXuatList()
        {
            InitializeComponent();
        }
        #endregion
        #region Functions
        private void KhoiTao()
        {
            db = new KhoDBContext();
            db.Saved += new EventHandler(db_Saved);
            listCongDoan = db.CongDoan
                .Include(c=>c.ThanhPham)
                .Include(c=>c.ChiTiet)
                .Where(c => c.TrangThai)
                .OrderBy(c=>c.NgayTao)
                .ToList();
            acs = new Access();
            //
            dt=new DataTable();
            //tạo các column
            DataColumn col;
            //Tạo column id
            col = new DataColumn("Id");
            col.DataType = System.Type.GetType("System.Guid");
            dt.Columns.Add(col);
            //Tạo column tên sản phẩm
            col = new DataColumn("TenThanhPham");
            col.DataType = System.Type.GetType("System.String");
            dt.Columns.Add(col);
            //Tạo column nguyên công
            int maxNC;
            if (listCongDoan.Count == 0)
                maxNC = 0;
            else
                maxNC = listCongDoan.OrderBy(l => l.ChiTiet.Count).LastOrDefault().ChiTiet.Count;
            for (int i = 0; i < maxNC; i++)
            {
                col = new DataColumn(string.Format("NC{0}", (i + 1).ToString()));
                col.DataType = System.Type.GetType("System.String");
                dt.Columns.Add(col);
            }
            //
            foreach (CongDoan item in listCongDoan)
            {
                int i=0;
                DataRow row=dt.NewRow();
                row[i] = item.Id;
                i++;
                row[i]=item.ThanhPham == null ? "":item.ThanhPham.TenMatHang;
                foreach (CongDoanChiTiet subitem in item.ChiTiet.OrderBy(c=>c.ThuTu).Where(c=>c.TrangThai))
                { 
                    i++;
                    row[i] = subitem.TenCongDoan;
                }
                dt.Rows.Add(row);
            }
            dgvCongDoanSanXuat.DataSource = dt;
            CustomerGridView();
        }

        private void ReLoadData()
        {
            if (db != null) db.Dispose();
            KhoiTao();
        }

        private void CustomerGridView()
        {
            //Khóa tính năng thêm mới
            dgvCongDoanSanXuat.AllowUserToAddRows = false;
            //Không cho edit
            dgvCongDoanSanXuat.ReadOnly = true;
            //Tùy chỉnh lại
            //Id
            var c = dgvCongDoanSanXuat.Columns["Id"];
            c.Visible = false;
            //Tên thành phẩm
            c = dgvCongDoanSanXuat.Columns["TenThanhPham"];
            c.Visible = true;
            c.HeaderText = "Thành Phẩm";
            c.Width = 200;
            c.DisplayIndex = 1;

        }

        private void HienThiChiTiet()
        {
            Guid Id =(Guid)dgvCongDoanSanXuat.CurrentRow.Cells["Id"].Value;
            if (Id == null || Id == Guid.Empty)
                return;
            CongDoan item = listCongDoan.FirstOrDefault(l => l.Id.Equals(Id));
            if (item != null)
            {
                frmCongDoanSanXuatDetail _frmCongDoanSanXuatDetail = new frmCongDoanSanXuatDetail();
                _frmCongDoanSanXuatDetail.DBChanged += new EventHandler(_frmCongDoanSanXuatDetail_DBChanged);
                acs.ShowFormCongDoanSanXuatDetail(_frmCongDoanSanXuatDetail, item.Id);
            }
        }

        private void Xoa()
        {
            Guid Id = (Guid)dgvCongDoanSanXuat.CurrentRow.Cells["Id"].Value;
            if (Id == null || Id == Guid.Empty)
                return;
            CongDoan item;
            item = db.CongDoan
                .Include(c => c.ChiTiet)
                .Include(c => c.ThanhPham)
                .FirstOrDefault(c => c.TrangThai && c.Id.Equals(Id));
            if (Common.ShowMessengerConfirmDelete() == DialogResult.Yes)
            {
                if (item != null)
                {
                   
                    //Xóa danh sách công đoạn chi tiết
                    List<CongDoanChiTiet> listCDCT;
                    listCDCT = db.CongDoanChiTiet
                        .Include(c => c.May)
                        .Include(c => c.CongDoan)
                        .Where(c => c.TrangThai
                            &&
                            c.CongDoan.Id.Equals(item.Id))
                        .ToList();
                    foreach (CongDoanChiTiet cdct in listCDCT)
                    {
                        db.CongDoanChiTiet.Remove(cdct);
                    }
                    //xóa công đoạn
                    item.TrangThai = false;
                    db.SaveChanges();
                }
            }
        }

        private void LuuLai()
        {
            if (Common.ShowMessengerConfirmSave() == DialogResult.Yes)
            {
                db.SaveChanges();
            }
        }
        private void ExportToExcel()
        {
            string workbookPath = Application.StartupPath + @"\Template\Excel\JAT_CongDoanSanXuat";
            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(workbookPath,
               0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "",
                true, false, 0, true, false, false);
            Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets[1];
            //xlWorkBook.Activate();
            xlWorkSheet.Name = "CongDoanSanXuat";
            //Add data
            int count = 0;
            int count2 = 0;
            int positonStart = 11;
            Excel.Range r;
            string start = "";
            string stop = "";
            foreach (CongDoan item in listCongDoan)
            {
                //Thay lại máy
                for (int i = 0; i < item.ChiTiet.Count; i++)
                {
                    Guid Id1 = item.ChiTiet[i].Id;
                    CongDoanChiTiet ct = db.CongDoanChiTiet.Include(c => c.May).FirstOrDefault(c => c.Id.Equals(Id1));
                    item.ChiTiet[i] = ct;

                }
                //
                item.ChiTiet = item.ChiTiet.OrderBy(c => c.ThuTu).ToList();
                foreach(CongDoanChiTiet subItem in item.ChiTiet)
                {
                    xlWorkSheet.Cells[positonStart + count2 , 4] = subItem.NguyenCong;
                    xlWorkSheet.Cells[positonStart + count2 , 5] = subItem.TenCongDoan;
                    xlWorkSheet.Cells[positonStart + count2 , 6] = subItem.May == null ? "" : subItem.May.TenMatHang;
                    xlWorkSheet.Cells[positonStart + count2 , 7] = subItem.DinhMuc;
                    count2++;
                }



                //Format it               

                start = "A" + (count2 - item.ChiTiet.Count + positonStart).ToString();
                stop = "G" + (count2 - 1 + positonStart).ToString();
                r = (Excel.Range)xlWorkSheet.get_Range(start, stop);
                r.Borders.Color = Color.Black;
                r.RowHeight = 30;
                //r.Style.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                r.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlDot;
                //r.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                //Xử lý cột STT
                start = "A" + (count2 - item.ChiTiet.Count + positonStart).ToString();
                stop = "A" + (count2 - 1 + positonStart).ToString();
                r = (Excel.Range)xlWorkSheet.get_Range(start, stop);
                r.Merge();
                r.Value2 = count + 1;
                r.Style.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                //Xử lý cột Mã Thành Phẩm
                start = "B" + (count2 - item.ChiTiet.Count + positonStart).ToString();
                stop = "B" + (count2 - 1 + positonStart).ToString();
                r = (Excel.Range)xlWorkSheet.get_Range(start, stop);
                r.Merge();
                r.Value2 = item.ThanhPham.MaMatHang;
                r.Value = item.ThanhPham.MaMatHang;
                //Xử lý cột Tên Thành Phẩm
                start = "C" + (count2 - item.ChiTiet.Count + positonStart).ToString();
                stop = "C" + (count2 - 1 + positonStart).ToString();
                r = (Excel.Range)xlWorkSheet.get_Range(start, stop);
                r.Merge();
                r.Value2 = item.ThanhPham.TenMatHang;
                r.Value = item.ThanhPham.TenMatHang;
                ////merge
                //start = "C" + (count + positonStart).ToString();
                //stop = "E" + (count + positonStart).ToString();
                //r = (Excel.Range)xlWorkSheet.get_Range(start, stop);
                //r.Merge();
                count++;
            }
            xlWorkSheet.Cells[7, 7] = string.Format("Ngày {0}/{1}/{2}", DateTime.Now.Day, DateTime.Now.Month, DateTime.Now.Year);
            // Hiện chương trình
            xlApp.Visible = true;

            //// Save file
            //xlWorkBook.SaveAs("C:\\JAT_VatTu_DanhMucThepDac_1.xls", Excel.XlFileFormat.xlWorkbookNormal,
            //                null, null, false, false,
            //                Excel.XlSaveAsAccessMode.xlExclusive,
            //                false, false, false, false, false);
            xlApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
        }
        #endregion
        #region Events

        private void frmCongDoanSanXuatList_Load(object sender, EventArgs e)
        {
            KhoiTao();
        }

        private void btnAddNew_Click(object sender, EventArgs e)
        {
            frmCongDoanSanXuatDetail _frmCongDoanSanXuatDetail = new frmCongDoanSanXuatDetail();
            _frmCongDoanSanXuatDetail.DBChanged += new EventHandler(_frmCongDoanSanXuatDetail_DBChanged);
            acs.ShowFormCongDoanSanXuatDetail(_frmCongDoanSanXuatDetail, Guid.Empty);
        }



        private void btnInformation_Click(object sender, EventArgs e)
        {
            HienThiChiTiet();
        }
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            ReLoadData();
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            Xoa();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dgvCongDoanSanXuat_DoubleClick(object sender, EventArgs e)
        {
            HienThiChiTiet();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            LuuLai();
        }

        void db_Saved(object sender, EventArgs e)
        {
            ReLoadData();
        }
        void _frmCongDoanSanXuatDetail_DBChanged(object sender, EventArgs e)
        {
            ReLoadData();
        }
        private void btnExport_Click(object sender, EventArgs e)
        {
            ExportToExcel();
        }
        #endregion


    }
}
